/**
 * worker进程，用于真正的业务处理
 */

var http = require("http");
var express = require("express");

//初始化express
var routes = require('../../routes/route');
var path = require('path');
var domain = require('domain');
var app = express();
var config = require("../../config/config");
var logger = require("../utils/logger");
var favicon = require("serve-favicon");
var cookieParser = require('cookie-parser');
var bodyParser = require("body-parser");
var methodOverride = require("method-override");
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
var chat = require('../chat/server');
var expressWinston = require('express-winston');

logger.info("服务器(pid: %s)开始启动。", process.pid);

// 设置环境变量
app.set('port', process.env.PORT || config.webServer.port);
app.set('views', __dirname + '/../../views');
app.set('view engine', 'ejs');

// 设置网站图标
app.use(favicon(__dirname + '/../../public/images/icon.jpg'));

app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(multipartMiddleware);
app.use(express.static(path.join(__dirname, '/../../', 'public')));
app.use(cookieParser());
app.use(expressWinston.logger({
    transports: config.logOptions.transports
}));

// 注册请求路径
routes.setup(app);
var httpServer = http.createServer(app);
// 启动聊天服务
chat.setup(httpServer);
// 开始进行监听
httpServer.listen(config.webServer.port, function () {
    logger.info("服务器(pid:%s)监听端口: %s", process.pid, config.webServer.port);

    var d = domain.create();
    d.on('error', function (err) {
        logger.error("uncaught exception: ", err.stack);
        //关闭服务
        httpServer.close(function () {
            logger.info("close http server.");
            process.disconnect();
        });

        //对于耗时的长连接，设置超时,进程退出
        setTimeout(function () {
            process.kill();
        }, config.webServer.timeout);
    });
});

// 接收关闭进程消息
process.on("message", function (_msg) {
    logger.warn("worker:onerror: 接收到系统消息. ", _msg);
    if (_msg === "shutdown") {
        //优雅的关闭掉所有的服务，并退出进程
        httpServer.close();
    }
});

// 接收错误消息
process.on("error", function (err) {
    logger.error("worker:onerror: ", err);
    process.destory();
});
